﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infrastructure.Model;
using Infrastructure.Model.DI;

using Microsoft.AspNetCore.Mvc.ActionConstraints;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Model.EntityModel.Auth;
using Service.IService.ISysService;

namespace Service.Service.SysService
{
  
    [AppService(ServiceType = typeof(IRouteInfoService), ServiceLifetime = LifeTime.Scoped)]
    public class RouteInfoService : IRouteInfoService
    {
        private readonly IActionDescriptorCollectionProvider _actionDescriptorCollectionProvider;

        public RouteInfoService(IActionDescriptorCollectionProvider actionDescriptorCollectionProvider)
        {
            _actionDescriptorCollectionProvider = actionDescriptorCollectionProvider;
        }

        public List<RouteInfo> GetAllRouteInformations()
        {
            var routes = new List<RouteInfo>();
            var actionDescriptors = _actionDescriptorCollectionProvider.ActionDescriptors.Items;

            foreach (var action in actionDescriptors)
            {
                // 获取控制器名称
                var controller = action.RouteValues["controller"];

                // 获取Action名称
                var actionName = action.RouteValues["action"];

                // 获取HTTP方法
                var httpMethod = action.ActionConstraints?
                    .OfType<HttpMethodActionConstraint>()
                    .FirstOrDefault()?
                    .HttpMethods?
                    .FirstOrDefault() ?? "ANY";

                // 获取路由模板
                var template = action.AttributeRouteInfo?.Template
                    ?? $"{controller}/{actionName}";

                routes.Add(new RouteInfo
                {
                    Controller = controller,
                    Action = actionName,
                    HttpMethod = httpMethod,
                    Template = template
                });
            }

            return routes;
        }
    }
}
